//
//  SelectedViewController.m
//  礼物go
//
//  Created by dllo on 16/5/16.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SelectedViewController.h"
#import "SelectTableViewCell.h"
#import "SelectTableHeaderView.h"
#import "SelectContentModel.h"
#import "SelectDetailViewController.h"
#import "CycleColumnViewController.h"

#import "LoginViewController.h"


static NSString *const selectCell = @"selectCell";

@interface SelectedViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *presentTableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIView *headerView;

@property(nonatomic,assign)NSInteger nextPage;//记录下一页
@property(nonatomic,assign)BOOL isUpLoading;//标记上拉操作还是下拉操作，yes为上拉


@end

@implementation SelectedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataArray = [NSMutableArray array];
    
    
    self.presentTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, self.view.frame.size.height - 140) style:UITableViewStylePlain];
    [self.view addSubview:self.presentTableView];
    self.presentTableView.showsVerticalScrollIndicator = NO;
    self.presentTableView.dataSource = self;
    self.presentTableView.delegate = self;
    [self.presentTableView registerClass:[SelectTableViewCell class] forCellReuseIdentifier:selectCell];

     [self getHeaderView];
    self.isUpLoading = NO;
   
    
    
    [self addHeader];
    [self addFooter];
    
    

    // Do any additional setup after loading the view.
}
-(void)setDataId:(NSString *)dataId{
    _dataId = dataId;
  [self getSelectList:0];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.presentTableView reloadData];

}
#pragma mark --下拉刷新
-(void)addHeader{
    __block SelectedViewController *selectVC = self;
     // 添加上拉刷新尾部控件
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
         selectVC.nextPage = 0;//记录页码
        selectVC.isUpLoading = NO;//标记为下拉操作
        [selectVC getSelectList:selectVC.nextPage];//重新请求数据
    }];
    #pragma mark 自动刷新(一进入程序就下拉刷新)
    //[header beginRefreshing];
    self.presentTableView.mj_header = header;
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    NSMutableArray *imageArray = [NSMutableArray array];
    for (int i = 1; i < 6; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"box_0%d",i]];
        [imageArray addObject:image];
    }
    [header setImages:imageArray forState:MJRefreshStateRefreshing];
    
    UIImage *pullImage = [imageArray firstObject];
    NSArray *pullArray = [NSArray arrayWithObjects:pullImage, nil];
   [header setImages:pullArray forState:MJRefreshStatePulling];
//    [header setImages:pullArray duration:2 forState:MJRefreshStateRefreshing];
}

#pragma mark --上拉加载更多
-(void)addFooter{
 __block SelectedViewController *selectVC = self;
    // 添加上拉刷新尾部控件
    self.presentTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        selectVC.nextPage ++;
        selectVC.isUpLoading = YES;//标记为上拉操作
        [selectVC getSelectList:selectVC.nextPage];//请求数据
        
    }];
}


-(void)getSelectList:(NSUInteger)nextCursor{
    
    AFNetworkReachabilityManager *netWorkManger = [AFNetworkReachabilityManager sharedManager];
    //****参数cursor的值: 第一页默认为0，下一页就是请求下来数据中next_cursor的值
    NSString *urlStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?gender=2&generation=4&limit=20&offset=%ld",self.dataId, 20 * nextCursor];
    
    [LYNetworking ly_GetWithURL:urlStr Parameter:nil success:^(id result) {
        [netWorkManger stopMonitoring];
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.dataArray removeAllObjects];
        }
        NSDictionary *dataDic = [result objectForKey:@"data"];
        NSArray *itemArray = [dataDic objectForKey:@"items"];
        for (NSDictionary *dic in itemArray) {
            SelectContentModel *contentModel = [[SelectContentModel alloc] init];
            [contentModel setValuesForKeysWithDictionary:dic];
            [self.dataArray addObject:contentModel];
        }
        [self.presentTableView.mj_header endRefreshing];
        [self.presentTableView.mj_footer endRefreshing];
        
        [self.presentTableView reloadData];
        
    } error:^(NSError *error) {
        
        
    }];
    
    
    
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript", nil];
//    [manager GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        [netWorkManger stopMonitoring];
//        if (self.isUpLoading == NO) {
//           //说明是下拉，就要清空数组中的数据
//            [self.dataArray removeAllObjects];
//        }
//        NSDictionary *dataDic = [responseObject objectForKey:@"data"];
//             NSArray *itemArray = [dataDic objectForKey:@"items"];
//             for (NSDictionary *dic in itemArray) {
//                 SelectContentModel *contentModel = [[SelectContentModel alloc] init];
//                 [contentModel setValuesForKeysWithDictionary:dic];
//                 [self.dataArray addObject:contentModel];
//             }
//        [self.presentTableView.mj_header endRefreshing];
//        [self.presentTableView.mj_footer endRefreshing];
//        
//             [self.presentTableView reloadData];
//
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        
//    }];
}

-(void)getId:(NSString *)dataId{
//    NSString *urlStr = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?gender=2&generation=4&limit=20&offset=0",dataId];
// [LYNetworking ly_GetWithURL:urlStr Parameter:nil success:^(id result) {
//     NSDictionary *dataDic = [result objectForKey:@"data"];
//     NSArray *itemArray = [dataDic objectForKey:@"items"];
//     for (NSDictionary *dic in itemArray) {
//         SelectContentModel *contentModel = [[SelectContentModel alloc] init];
//         [contentModel setValuesForKeysWithDictionary:dic];
//         [self.dataArray addObject:contentModel];
//     }
//     [self.presentTableView reloadData];
//     
// } error:^(NSError *error) {
//     
//     
// }];
   // self.dataId = dataId;
   // NSLog(@"%@",self.dataId);
}

-(void)getHeaderView{
    SelectTableHeaderView *headerView = [[SelectTableHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 320)];
    self.presentTableView.tableHeaderView = headerView;
    
    __block SelectedViewController *selectVC = self;
    headerView.selPushBlock = ^(CycleViewModel *cycleModel){
        if ([cycleModel.target_id integerValue] < 10000) {
            CycleColumnViewController *cyCVC = [[CycleColumnViewController alloc] init];
            cyCVC.dataId = cycleModel.target_id;
            
            [selectVC.navigationController pushViewController:cyCVC animated:YES];
        }
        
        if ([cycleModel.target_id integerValue] > 10000) {
         SelectDetailViewController *SDVC = [[SelectDetailViewController alloc] init];
            //NSString *urlString = [NSString stringWithFormat:@"http://www.liwushuo.com/posts/%@",cycleModel.target_id];
            NSNumber *dataId = @([cycleModel.target_id integerValue]);
            SDVC.dataId = dataId;
            SDVC.hidesBottomBarWhenPushed = YES;
            [selectVC.navigationController pushViewController:SDVC animated:YES];
        }
};
    
    headerView.cycPushBlock = ^(NSString *dataId){
        CycleColumnViewController *cyCollVC = [[CycleColumnViewController alloc] init];
        cyCollVC.dataId = dataId;
        [selectVC.navigationController pushViewController:cyCollVC animated:YES];
        
    };

}

//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 15;
//}



//-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 3;
//}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:selectCell];
    SelectContentModel *selectModel = [self.dataArray objectAtIndex:indexPath.row];
    cell.selectContent = selectModel;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    __block SelectedViewController *selectVC = self;
    cell.likePush = ^(){
            LoginViewController *loginVC = [[LoginViewController alloc] init];
            [selectVC presentViewController:loginVC animated:YES completion:^{
                
                
            }];
    };
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SelectContentModel *selectModel = [self.dataArray objectAtIndex:indexPath.row];
    SelectDetailViewController *SDVC = [[SelectDetailViewController alloc] init];
    SDVC.dataId = selectModel.myId;
    SDVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:SDVC animated:YES];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
